package com.tzpay.tzpay.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tzpay.tzpay.R;
import com.tzpay.tzpay.bean.OrderInfo;
import com.tzpay.tzpay.bean.UserInfo;
import com.tzpay.tzpay.db.OrderDBUtil;
import com.tzpay.tzpay.ui.BaseActivity;
import com.tzpay.tzpay.ui.fragment.AcquiringFragment;
import com.tzpay.tzpay.ui.fragment.HomeFragment;
import com.tzpay.tzpay.ui.fragment.MeFragment;
import com.tzpay.tzpay.ui.fragment.TradeListFragment;
import com.tzpay.tzpay.utils.AppManager;
import com.tzpay.tzpay.utils.SPUtil;
import com.tzpay.tzpay.utils.T;
import com.tzpay.tzpay.view.CustomDialogBuilder;
import com.tzpay.tzpay.view.DraggableFlagView;

import java.lang.ref.SoftReference;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by chenfeiyue on 16/4/7.
 */
public class MainActivity extends BaseActivity implements DraggableFlagView.OnDraggableFlagViewListener {

    @Bind(R.id.iv_bottom_home)
    ImageView ivBottomHome;
    @Bind(R.id.tv_bottom_home)
    TextView tvBottomHome;
    @Bind(R.id.iv_bottom_message)
    ImageView ivBottomMessage;
    @Bind(R.id.tv_bottom_message)
    TextView tvBottomMessage;
    @Bind(R.id.iv_bottom_me)
    ImageView ivBottomMe;
    @Bind(R.id.tv_bottom_me)
    TextView tvBottomMe;
    @Bind(R.id.main_dfv)
    DraggableFlagView dfvNewMsgNum;

    public static final int FLAG_HOME_TAB = 1;
    public static final int FLAG_MESSAGE_TAB = 2;
    public static final int FLAG_ME_TAB = 3;
    private SoftReference<AcquiringFragment> homeFragmentSoftRefer;
    private SoftReference<TradeListFragment> tradeFragmentSoftRefer;
    private SoftReference<MeFragment> meFragmentSoftRefer;
    private Fragment currentFragment;

    private static final String TAG = MainActivity.class.getSimpleName();

    private DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            AppManager.finishAllActivity();
        }
    };

    private void renderNewMessageNumber() {
        SPUtil spUtil = SPUtil.getInstance(this);
        int newMsgNum = spUtil.getInt(SPUtil.SPKey.NEW_MESSAGE_NUMBER, 0);
        if (newMsgNum != 0) {
            dfvNewMsgNum.setVisibility(View.VISIBLE);
            dfvNewMsgNum.setText(newMsgNum + "");
        } else {
            dfvNewMsgNum.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && intent.getIntExtra("tab", FLAG_HOME_TAB) == FLAG_MESSAGE_TAB) {
            presseTab(FLAG_MESSAGE_TAB);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasAppBar(false);
//        UmengUpdateAgent.setDefault();
//        UmengUpdateAgent.update(getApplication());
        dfvNewMsgNum.setOnDraggableFlagViewListener(this);
        renderNewMessageNumber();
        if (getIntent() != null && getIntent().getIntExtra("tab", FLAG_HOME_TAB) == FLAG_MESSAGE_TAB) {
            presseTab(FLAG_MESSAGE_TAB);
        } else {
            presseTab(FLAG_HOME_TAB);
        }
//        test();
    }

    @Override
    public void setupContentView() {
        setContentView(R.layout.activity_main);
    }

    private void presseTab(int tabFlag) {
        switch (tabFlag) {
            case FLAG_HOME_TAB:
                tvBottomHome.setEnabled(true);
                ivBottomHome.setEnabled(true);
                tvBottomMe.setEnabled(false);
                ivBottomMe.setEnabled(false);
                ivBottomMessage.setEnabled(false);
                tvBottomMessage.setEnabled(false);
                showHomeFragment();

                break;
            case FLAG_ME_TAB:
                tvBottomHome.setEnabled(false);
                ivBottomHome.setEnabled(false);
                tvBottomMe.setEnabled(true);
                ivBottomMe.setEnabled(true);
                ivBottomMessage.setEnabled(false);
                tvBottomMessage.setEnabled(false);
                showMeFragment();

                break;
            case FLAG_MESSAGE_TAB:
                tvBottomHome.setEnabled(false);
                ivBottomHome.setEnabled(false);
                tvBottomMe.setEnabled(false);
                ivBottomMe.setEnabled(false);
                ivBottomMessage.setEnabled(true);
                tvBottomMessage.setEnabled(true);
                showMessageFragment();
                break;
            default:
                break;
        }
    }

    /**
     * 绘制Fragment到屏幕中间  如果已经添加到事务中，则进行显示和隐藏操作
     *
     * @param fragment 需要推入的Fragment
     */
    public void showMainFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //隐藏之前显示的fragment
        if (currentFragment != null && currentFragment != fragment) {
            transaction.hide(currentFragment);
        }
        if (currentFragment != fragment) {
            this.currentFragment = fragment;
            //需要显示的fragment
            if (fragment.isAdded()) {
                transaction.show(fragment);
            } else {
                transaction.add(R.id.rl_main_container, fragment);
            }
            transaction.commitAllowingStateLoss();
        }
    }

    public void showHomeFragment() {
        if (homeFragmentSoftRefer == null || homeFragmentSoftRefer.get() == null) {
            homeFragmentSoftRefer = new SoftReference<>(AcquiringFragment.instance());
        }
        showMainFragment(homeFragmentSoftRefer.get());
    }

    public void showMessageFragment() {
        if (tradeFragmentSoftRefer == null || tradeFragmentSoftRefer.get() == null) {
            tradeFragmentSoftRefer = new SoftReference<>(TradeListFragment.instance());
        }
        showMainFragment(tradeFragmentSoftRefer.get());
    }

    public void showMeFragment() {
        if (meFragmentSoftRefer == null || meFragmentSoftRefer.get() == null) {
            meFragmentSoftRefer = new SoftReference<>(MeFragment.instance());
        }
        showMainFragment(meFragmentSoftRefer.get());
    }

    @Override
    public void onFlagDismiss(DraggableFlagView view) {
        T.e(TAG, "onFlagDismiss");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 返回键的处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handleBackReturnEvent();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick(R.id.ll_tab_home)
    public void onTabHomeClicked() {
        presseTab(FLAG_HOME_TAB);
    }

    @OnClick(R.id.ll_tab_me)
    public void onTabMeClicked() {
        presseTab(FLAG_ME_TAB);
    }

    @OnClick(R.id.ll_tab_message)
    public void onTabMessageClicked() {
        presseTab(FLAG_MESSAGE_TAB);
    }

    private void handleBackReturnEvent() {
        showNormalDialog(getString(R.string.text_tip), getString(R.string.text_message), clickListener, null);
    }

    protected void showNormalDialog(String title, String message, final DialogInterface.OnClickListener okListener, final DialogInterface.OnClickListener cancelListener) {
        CustomDialogBuilder.buildDoubleBtnDialog(this)
                .setMsg(message)
                .setConfirmBtnText(getString(R.string.text_ok))
                .setTouchOutsideCanDismiss(true)
                .setOnConfrimClickListener(new CustomDialogBuilder.OnConfrimClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog) {
                        if (null != dialog) dialog.dismiss();
                        if (null == okListener) return;
                        okListener.onClick(dialog, 1);
                    }
                })
                .setCancelBtnText(getString(R.string.text_cancel))
                .setCancelClickListener(new CustomDialogBuilder.OnCancelCLickListener() {
                    @Override
                    public void onClick(DialogInterface dialog) {
                        if (null != dialog) dialog.dismiss();
                        if (null == cancelListener) return;
                        cancelListener.onClick(dialog, 0);

                    }
                }).getDialog().show();
    }

    private void test() {

        Context context = MainActivity.this.getApplicationContext();
        OrderDBUtil.getInstance(context).initDB();

//        createOrderInfo(MainActivity.this.getApplicationContext());

        updateOrInsertOrderInfo(context);
    }

    /**
     * 创建MultiOrderInfo，存入数据库
     *
     * @param context
     */
    private OrderInfo createOrderInfo(Context context) {
        OrderInfo mediaInfo = new OrderInfo();
        // 存入数据库
        OrderDBUtil.getInstance(context).insert(mediaInfo);
        return mediaInfo;
    }

    private void updateOrInsertOrderInfo(Context context) {
        OrderInfo orderInfo = new OrderInfo();

        for (int i = 100; i < 200; i++) {
            orderInfo.setOrderNo(i + "");
            orderInfo.setOrderAmt(i + "");
            orderInfo.setAttachAmt(i + "");
            orderInfo.setTransStatus("A");
            orderInfo.setMerchantId(UserInfo.getInstance().getMerchantNo());
            if (i % 3 == 0) {
                orderInfo.setTransStatus("B");
            } else if (i % 4 == 0) {
                orderInfo.setTransStatus("C");
            } else if (i % 5 == 0) {
                orderInfo.setTransStatus("G");
            }
//            OrderDBUtil.getInstance(context).updateOrInsert(orderInfo);
            OrderDBUtil.getInstance(context).insert(orderInfo);
        }
    }

//    @Override
//    public void reLogin() {
//        UserCache.getInstance(this).clearUserCache();
//        Intent intent = new Intent(this, LoginActivity.class);
//        startActivity(intent);
//        finish();
//    }

}
